import React, {useState} from 'react';
import {
	ActivityIndicator,
	Alert,
	Image,
	RefreshControl,
	ScrollView,
	StyleSheet,
	Text,
	TouchableOpacity,
	View
} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {useFocusEffect, useNavigation} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import {Ionicons} from '@expo/vector-icons';
import {LinearGradient} from 'expo-linear-gradient';
import {RootStackParamList} from '../navigation/AppNavigator';
import {Colors} from '../constants/colors';
import {profileService} from '../services';
import {UserProfileVo} from '../types/api';
import {AuthManager} from '../utils/api';

type PersonalCenterNavigationProp = StackNavigationProp<RootStackParamList>;

interface MenuItem {
	id: string;
	title: string;
	icon: keyof typeof Ionicons.glyphMap;
	onPress: () => void;
}

export default function PersonalCenterScreen() {
	const navigation = useNavigation<PersonalCenterNavigationProp>();
	const [profile, setProfile] = useState<UserProfileVo | null>(null);
	const [loading, setLoading] = useState(true);
	const [refreshing, setRefreshing] = useState(false);

	// 加载用户资料
	const loadProfile = async () => {
		try {
			setLoading(true);
			const profileData = await profileService.getProfile();
			setProfile(profileData);
		} catch (error: any) {
			console.error('加載用戶資料失敗:', error);
			Alert.alert('錯誤', '加載用戶資料失敗: ' + (error.message || '未知錯誤'));
		} finally {
			setLoading(false);
		}
	};

	// 下拉刷新处理
	const onRefresh = async () => {
		setRefreshing(true);
		await loadProfile();
		// 延迟一点时间再隐藏刷新指示器，提供更好的用户体验
		setTimeout(() => {
			setRefreshing(false);
		}, 500);
	};

	// 页面聚焦时重新加载数据
	useFocusEffect(
		React.useCallback(() => {
			loadProfile();
		}, [])
	);

	// 退出登录处理
	const handleLogout = () => {
		Alert.alert(
			'確認退出',
			'您確定要退出登錄嗎？',
			[
				{
					text: '取消',
					style: 'cancel',
				},
				{
					text: '退出',
					style: 'destructive',
					onPress: async () => {
						try {
							// 清除本地存储的token
							await AuthManager.setToken('');

							// 跳转到登录页面
							navigation.reset({
								index: 0,
								routes: [{name: 'AuthLanding'}],
							});
						} catch (error) {
							console.error('退出登錄失敗:', error);
							Alert.alert('錯誤', '退出登錄失敗，請重試');
						}
					},
				},
			]
		);
	};

	// 前往认证处理
	const handleGoToAuth = () => {
		navigation.navigate('RoleSelect');
	};

	// 根据用户类型动态生成菜单项
	const getMenuItems = (): MenuItem[] => {
		const items: MenuItem[] = [];
		console.log(profile, 'profile==========');
		// 如果用户未认证（auditState为null或undefined），只显示前往认证和退出登录
		if (profile?.auditState === null || profile?.auditState === undefined) {
			items.push({
				id: 'go-to-auth',
				title: '前往認證',
				icon: 'person-add-outline',
				onPress: handleGoToAuth,
			});
			items.push({
				id: 'logout',
				title: '退出登錄',
				icon: 'log-out-outline',
				onPress: handleLogout,
			});
			return items;
		}

		// 运动记录 - 所有已认证用户都有
		items.push({
			id: 'exercise-records',
			title: '運動記錄',
			icon: 'fitness',
			onPress: () => navigation.navigate('ExerciseRecords'),
		});

		// 如果是商家，显示导师管理和课程管理
		if (profile?.merchant && profile?.auditState != 0) {
			items.push({
				id: 'instructor-management',
				title: '導師管理',
				icon: 'people',
				onPress: () => navigation.navigate('InstructorManagement'),
			});
		}

		// 如果是商家或导师，显示课程管理（但只显示一次）
		if ((profile?.merchant || profile?.mentor) && profile?.auditState != 0) {
			items.push({
				id: 'course-management',
				title: '課程管理',
				icon: 'book',
				onPress: () => navigation.navigate('CourseManagement'),
			});
		}

		// 临时显示所有菜单项用于测试（仅当已认证但不是商家或导师时）
		// if (!profile?.merchant && !profile?.mentor && profile?.auditState !== null && profile?.auditState !== undefined) {
		// 	items.push({
		// 		id: 'instructor-management',
		// 		title: '導師管理',
		// 		icon: 'people',
		// 		onPress: () => navigation.navigate('InstructorManagement'),
		// 	});
		// 	items.push({
		// 		id: 'course-management',
		// 		title: '課程管理',
		// 		icon: 'book',
		// 		onPress: () => navigation.navigate('CourseManagement'),
		// 	});
		// }

		// 退出登录 - 所有用户都有
		items.push({
			id: 'logout',
			title: '退出登錄',
			icon: 'log-out-outline',
			onPress: handleLogout,
		});

		return items;
	};

	const menuItems = getMenuItems();
	const getAccountStatusName = (val: UserProfileVo | null): string => {
		const titleMap: Record<number, string> = {
			0: '已確認',
			1: '禁用',
			2: '未確認',
		};
		const status = val?.accountStatus;
		if (status === null || status === undefined) return '未知';
		return titleMap[status] ?? '未知';
	}
	const renderMenuItem = (item: MenuItem) => (
		<TouchableOpacity
			key={item.id}
			style={styles.menuItem}
			onPress={item.onPress}
			activeOpacity={0.7}
		>
			<View style={styles.menuItemLeft}>
				<View style={styles.menuItemIcon}>
					<Ionicons name={item.icon} size={20} color={Colors.gray[600]}/>
				</View>
				<Text style={styles.menuItemTitle}>{item.title}</Text>
			</View>
			<Ionicons name="chevron-forward" size={20} color={Colors.gray[400]}/>
		</TouchableOpacity>
	);

	if (loading) {
		return (
			<SafeAreaView style={styles.container}>
				<View style={styles.loadingContainer}>
					<ActivityIndicator size="large" color={Colors.primary}/>
					<Text style={styles.loadingText}>加載中...</Text>
				</View>
			</SafeAreaView>
		);
	}

	return (
		<SafeAreaView style={styles.container}>
			<ScrollView
				style={styles.scrollView}
				showsVerticalScrollIndicator={false}
				refreshControl={
					<RefreshControl
						refreshing={refreshing}
						onRefresh={onRefresh}
						colors={[Colors.primary]}
						tintColor={Colors.primary}
					/>
				}
			>
				{/* Profile Header */}
				<LinearGradient
					colors={[Colors.gradientStart, Colors.gradientEnd]}
					start={{x: 0, y: 0}}
					end={{x: 1, y: 0}}
					style={styles.headerGradient}
				>
					<View style={styles.profileHeader}>
						<View style={styles.profileInfo}>
							<Image
								source={{
									uri: profile?.avatar || 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?ixlib=rb-4.0.3&auto=format&fit=crop&w=80&h=80',
								}}
								style={styles.profileImage}
							/>
							<View style={styles.profileText}>
								<View style={styles.nameRow}>
									<Text style={styles.profileName}>
										{profile?.nickName || '用戶'}
									</Text>
									{/* 认证状态标签 - 第一个标签 */}
									<View style={[
										styles.inlineStatusTag,
										(profile?.auditState === null || profile?.auditState === undefined) ? styles.grayTag :
											(profile?.auditState == 0) ? styles.orangeTag :
												(profile?.auditState == 1 && profile?.merchant) ? styles.blueTag :
													(profile?.auditState == 1 && profile?.mentor) ? styles.purpleTag :
														styles.redTag
									]}>
										<Text style={styles.inlineStatusText}>
											{(profile?.auditState === null || profile?.auditState === undefined) ? '待審核' :
												profile.auditState == 0 ? '待審核' :
													profile.auditState == 1 && profile?.merchant ? '商家認證' :
														profile.auditState == 1 && profile?.mentor ? '導師認證' :
															profile.auditState == 2 ? '審核拒絕' : '未知'}
										</Text>
									</View>
									<View style={[
										styles.inlineStatusTag,
										(profile?.accountStatus === null || profile?.accountStatus === undefined) ? styles.grayTag :
											(profile?.accountStatus == 0) ? styles.orangeTag :
												(profile?.accountStatus == 1 && profile?.merchant) ? styles.blueTag :
													(profile?.accountStatus == 1 && profile?.mentor) ? styles.purpleTag :
														styles.redTag
									]}>
										<Text style={styles.inlineStatusText}>
											{getAccountStatusName(profile)}
										</Text>
									</View>
								</View>

								{/* 实名信息 - 显示displayName字段 */}
								{profile?.displayName && profile?.auditState == '1' && (
									<View style={styles.realNameRow}>
										<Ionicons name="checkmark-circle" size={16} color={Colors.white}/>
										<Text style={styles.realNameText}>
											{profile.displayName}
										</Text>
									</View>
								)}
							</View>
						</View>
						<TouchableOpacity style={styles.profileEditButton}
						                  onPress={() => navigation.navigate('ProfileEdit')}>
							<Ionicons name="chevron-forward" size={20} color={Colors.white}/>
						</TouchableOpacity>
					</View>

					{/* Decorative circles */}
					<View style={styles.decorativeCircle1}/>
					<View style={styles.decorativeCircle2}/>
				</LinearGradient>

				{/* Menu Items */}
				<View style={styles.menuContainer}>
					{menuItems.map(renderMenuItem)}
				</View>
			</ScrollView>
		</SafeAreaView>
	);
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: Colors.white,
	},
	loadingContainer: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
	},
	loadingText: {
		marginTop: 16,
		fontSize: 16,
		color: Colors.gray[600],
	},
	scrollView: {
		flex: 1,
	},
	headerGradient: {
		position: 'relative',
		paddingVertical: 32,
		paddingHorizontal: 24,
		overflow: 'hidden',
	},
	profileHeader: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		zIndex: 1,
	},
	profileInfo: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	profileImage: {
		width: 64,
		height: 64,
		borderRadius: 32,
		marginRight: 16,
		borderWidth: 3,
		borderColor: Colors.white,
	},
	profileText: {
		flex: 1,
	},
	nameRow: {
		flexDirection: 'row',
		alignItems: 'center',
		flexWrap: 'wrap',
		marginBottom: 4,
	},
	profileName: {
		fontSize: 24,
		fontWeight: 'bold',
		color: Colors.white,
		marginRight: 8,
	},
	inlineStatusTag: {
		paddingHorizontal: 8,
		paddingVertical: 3,
		borderRadius: 12,
		marginRight: 6,
		marginBottom: 2,
	},
	greenTag: {
		backgroundColor: '#22c55e',
	},
	redTag: {
		backgroundColor: '#ef4444',
	},
	grayTag: {
		backgroundColor: '#6b7280',
	},
	orangeTag: {
		backgroundColor: '#f97316',
	},
	blueTag: {
		backgroundColor: '#3b82f6',
	},
	purpleTag: {
		backgroundColor: '#8b5cf6',
	},
	realNameRow: {
		flexDirection: 'row',
		alignItems: 'center',
		marginTop: 4,
	},
	realNameText: {
		color: Colors.white,
		fontSize: 12,
		fontWeight: '500',
		marginLeft: 4,
		opacity: 0.9,
	},
	inlineStatusText: {
		fontSize: 10,
		fontWeight: '600',
		color: Colors.white,
	},
	profileBadge: {
		flexDirection: 'row',
		alignItems: 'center',
		backgroundColor: 'rgba(255, 255, 255, 0.2)',
		paddingHorizontal: 12,
		paddingVertical: 4,
		borderRadius: 16,
		alignSelf: 'flex-start',
	},
	profileBadgeText: {
		color: Colors.white,
		fontSize: 12,
		fontWeight: '500',
		marginLeft: 4,
	},

	profileEditButton: {
		width: 32,
		height: 32,
		alignItems: 'center',
		justifyContent: 'center',
		marginRight: 8, // 向左移动箭头
	},
	decorativeCircle1: {
		position: 'absolute',
		top: -40,
		right: -40,
		width: 160,
		height: 160,
		borderRadius: 80,
		borderWidth: 2,
		borderColor: 'rgba(255, 255, 255, 0.2)',
	},
	decorativeCircle2: {
		position: 'absolute',
		top: -24,
		right: -24,
		width: 128,
		height: 128,
		borderRadius: 64,
		borderWidth: 2,
		borderColor: 'rgba(255, 255, 255, 0.2)',
	},
	menuContainer: {
		paddingHorizontal: 16,
		paddingTop: 16,
	},
	settingsContainer: {
		paddingHorizontal: 16,
		paddingTop: 24,
		paddingBottom: 32,
	},
	menuItem: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		paddingVertical: 16,
		paddingHorizontal: 16,
		backgroundColor: Colors.white,
		borderRadius: 16,
		marginBottom: 12,
		elevation: 2,
		shadowColor: Colors.black,
		shadowOffset: {
			width: 0,
			height: 1,
		},
		shadowOpacity: 0.1,
		shadowRadius: 4,
	},
	menuItemLeft: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	menuItemIcon: {
		width: 40,
		height: 40,
		backgroundColor: Colors.gray[100],
		borderRadius: 12,
		alignItems: 'center',
		justifyContent: 'center',
		marginRight: 16,
	},
	menuItemTitle: {
		fontSize: 16,
		fontWeight: '500',
		color: Colors.gray[800],
	},
});
